package binarysearch;

/**
 * @Description 剑指 Offer II 006. 排序数组中两个数字之和
 * @Author Firenut
 * @Date 2023-04-16 21:09
 */
public class TII006_twoSum {
    // 法2: 双指针
    public int[] twoSumV2(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        while (left < right) {
            int ans = numbers[left] + numbers[right];
            if (ans < target) {
                left++;
            } else if (ans == target) {
                return new int[]{left, right};
            }else {
                right--;
            }
        }
        return new int[0];
    }

    // 法1:  有序数组,可用二分
    public int[] twoSum(int[] numbers, int target) {
        for (int i = 0; i < numbers.length; i++) {
            int index = binarySearch(numbers, i+1, numbers.length - 1, target - numbers[i]);
            if (index != -1) {
                return new int[]{i,index};
            }
        }
        return new int[0];
    }

    int binarySearch(int[] numbers, int left, int right, int target) {
        while (left <= right) {
            // 注意条件: left <= right
            int mid = left + (right - left)/2;
            if (numbers[mid] < target) {
                left = mid + 1;
            } else if (numbers[mid] == target) {
                return mid;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}
